#!/usr/bin/python
# coding:utf-8

from flask import abort
import pymysql
from dbpool import create_cursor
import uuid


def read_list():
    with create_cursor() as (conn, cursor):
        try:
            cursor.execute('SELECT * FROM umc.org')
            return cursor.fetchall()
        except pymysql.MySQLError as e:
            abort(500, e.args[1])


def create(data):
    data['gid'] = str(uuid.uuid4())
    with create_cursor() as (conn, cursor):
        try:
            conn.begin()
            sql = 'INSERT INTO umc.org (`gid`, `name`) VALUES (%s, %s)'
            cursor.execute(sql, (data.get('gid'), data.get('name')))
            conn.commit()
            return read(data.get('gid'))
        except pymysql.MySQLError as e:
            conn.rollback()
            abort(500, e.args[1])

    return None


def read(gid):
    with create_cursor() as (conn, cursor):
        try:
            cursor.execute('SELECT * FROM umc.org WHERE gid=%s', gid)
            return cursor.fetchone()
        except pymysql.MySQLError as e:
            abort(500, e.args[1])


def update(gid, data):
    obj = read(gid)
    obj.update(data)
    with create_cursor() as (conn, cursor):
        try:
            conn.begin()
            sql = 'UPDATE `umc`.`org` SET `name`=%s, `status`=%s WHERE `gid`=%s'
            cursor.execute(sql, (obj.get('name'), obj.get('status'), gid))
            conn.commit()
            return obj
        except pymysql.MySQLError as e:
            conn.rollback()
            abort(500, e.args[1])


def delete(gid):
    abort(501)

